<template>
  <div class="dashboard-container">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="welcome-content">
        <div class="welcome-text">
          <div class="ai-title-row">
            <svg-icon icon-class="ai-assistant" class="ai-icon" />
            <h2>智能办公，让工作更高效！</h2>
          </div>
          <p class="welcome-subtitle">
            AI助力，开启高效一天！您的专属智能办公助手
          </p>
          <p>{{ getGreeting() }}，今天是 {{ currentDate }}</p>
        </div>
        <div class="welcome-avatar">
          <el-avatar :size="60" :src="avatar">
            <i class="el-icon-user"></i>
          </el-avatar>
          <svg-icon icon-class="ai-assistant" class="ai-badge" />
        </div>
      </div>
      <div class="banner-wave"></div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col
        :xs="12"
        :sm="12"
        :lg="6"
        v-for="(item, index) in statsData"
        :key="index"
      >
        <div
          class="stats-card"
          :class="`stats-card-${index + 1}`"
          @click="handleCardClick(item)"
        >
          <div class="stats-icon">
            <i :class="item.icon"></i>
          </div>
          <div class="stats-content">
            <div class="stats-value">
              <count-to :start-val="0" :end-val="item.value" :duration="2000" />
            </div>
            <div class="stats-title">{{ item.title }}</div>
            <div class="stats-trend" v-if="item.trend">
              <i :class="item.trend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
              <span :class="item.trend > 0 ? 'trend-up' : 'trend-down'">
                {{ Math.abs(item.trend) }}%
              </span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧：日程 -->
      <el-col :lg="16" :md="24" class="left-col">
        <el-card class="schedule-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="header-title">
              <i class="el-icon-date"></i>
              日程
            </span>
            <el-radio-group
              v-model="scheduleTab"
              size="mini"
              style="margin-left: 16px"
            >
              <el-radio-button label="today">今日</el-radio-button>
              <el-radio-button label="week">本周</el-radio-button>
              <el-radio-button label="upcoming">即将到来</el-radio-button>
            </el-radio-group>
            <el-button type="text" @click="goToSchedule">
              查看全部 <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          <div class="schedule-content">
            <div v-if="scheduleTab === 'today'">
              <div v-if="todaySchedules.length === 0" class="empty-schedule">
                <i class="el-icon-date"></i>
                <p>今天没有安排日程</p>
                <el-button type="primary" size="small" @click="addSchedule">
                  添加日程
                </el-button>
              </div>
              <div v-else class="schedule-list">
                <div
                  v-for="schedule in todaySchedules"
                  :key="schedule.id"
                  class="schedule-item"
                  :class="{ urgent: isUrgent(schedule) }"
                >
                  <div class="schedule-time">
                    <div class="time">{{ formatTime(schedule.startTime) }}</div>
                    <div class="duration">
                      {{ getDuration(schedule.startTime, schedule.endTime) }}
                    </div>
                  </div>
                  <div class="schedule-info">
                    <div class="schedule-title">{{ schedule.title }}</div>
                    <div class="schedule-status">
                      <el-tag
                        :type="getScheduleStatus(schedule).type"
                        size="mini"
                        style="margin-right: 8px"
                      >
                        {{ getScheduleStatus(schedule).text }}
                      </el-tag>
                    </div>
                    <div class="schedule-location" v-if="schedule.location">
                      <i class="el-icon-location"></i>
                      {{ schedule.location }}
                    </div>
                    <div
                      class="schedule-participants"
                      v-if="schedule.participants"
                    >
                      <i class="el-icon-user"></i>
                      {{ schedule.participants.join(", ") }}
                    </div>
                  </div>
                  <div class="schedule-actions">
                    <el-button
                      type="text"
                      size="mini"
                      @click="editSchedule(schedule)"
                    >
                      <i class="el-icon-edit"></i>
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            <div v-else-if="scheduleTab === 'week'">
              <div v-if="weekSchedules.length === 0" class="empty-schedule">
                <i class="el-icon-date"></i>
                <p>本周没有安排日程</p>
              </div>
              <div v-else class="schedule-list">
                <div
                  v-for="schedule in weekSchedules"
                  :key="schedule.id"
                  class="schedule-item"
                  :class="{ urgent: isUrgent(schedule) }"
                >
                  <div class="schedule-time">
                    <div class="time">{{ formatTime(schedule.startTime) }}</div>
                    <div class="duration">
                      {{ getDuration(schedule.startTime, schedule.endTime) }}
                    </div>
                  </div>
                  <div class="schedule-info">
                    <div class="schedule-title">{{ schedule.title }}</div>
                    <div class="schedule-status">
                      <el-tag
                        :type="getScheduleStatus(schedule).type"
                        size="mini"
                        style="margin-right: 8px"
                      >
                        {{ getScheduleStatus(schedule).text }}
                      </el-tag>
                    </div>
                    <div class="schedule-location" v-if="schedule.location">
                      <i class="el-icon-location"></i>
                      {{ schedule.location }}
                    </div>
                    <div
                      class="schedule-participants"
                      v-if="schedule.participants"
                    >
                      <i class="el-icon-user"></i>
                      {{ schedule.participants.join(", ") }}
                    </div>
                  </div>
                  <div class="schedule-actions">
                    <el-button
                      type="text"
                      size="mini"
                      @click="editSchedule(schedule)"
                    >
                      <i class="el-icon-edit"></i>
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            <div v-else>
              <div v-if="upcomingSchedules.length === 0" class="empty-schedule">
                <i class="el-icon-date"></i>
                <p>暂无即将到来的日程</p>
              </div>
              <div v-else class="schedule-list">
                <div
                  v-for="schedule in upcomingSchedules"
                  :key="schedule.id"
                  class="schedule-item"
                  :class="{ urgent: isUrgent(schedule) }"
                >
                  <div class="schedule-time">
                    <div class="time">{{ formatTime(schedule.startTime) }}</div>
                    <div class="duration">
                      {{ getDuration(schedule.startTime, schedule.endTime) }}
                    </div>
                  </div>
                  <div class="schedule-info">
                    <div class="schedule-title">{{ schedule.title }}</div>
                    <div class="schedule-status">
                      <el-tag
                        :type="getScheduleStatus(schedule).type"
                        size="mini"
                        style="margin-right: 8px"
                      >
                        {{ getScheduleStatus(schedule).text }}
                      </el-tag>
                    </div>
                    <div class="schedule-location" v-if="schedule.location">
                      <i class="el-icon-location"></i>
                      {{ schedule.location }}
                    </div>
                    <div
                      class="schedule-participants"
                      v-if="schedule.participants"
                    >
                      <i class="el-icon-user"></i>
                      {{ schedule.participants.join(", ") }}
                    </div>
                  </div>
                  <div class="schedule-actions">
                    <el-button
                      type="text"
                      size="mini"
                      @click="editSchedule(schedule)"
                    >
                      <i class="el-icon-edit"></i>
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <!-- 新增：我的周报卡片 -->
        <el-card
          class="weekly-report-card"
          shadow="hover"
          style="margin-top: 20px"
        >
          <div slot="header" class="card-header">
            <span class="header-title">
              <i class="el-icon-data-analysis"></i>
              我的周报/日报
            </span>
            <el-button type="text" @click="goToReportHistory">
              更多 <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          <div class="weekly-report-content">
            <div v-if="weeklyReports.length === 0" class="empty-weekly-report">
              <i class="el-icon-document"></i>
              <p>暂无周报/日报</p>
            </div>
            <div v-else class="weekly-report-list">
              <div
                v-for="report in weeklyReports"
                :key="report.reportId"
                class="weekly-report-item"
                @click="previewReport(report)"
                style="
                  cursor: pointer;
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  padding: 8px 0;
                "
              >
                <div>
                  <el-tag
                    :type="
                      report.reportType === 'weekly' ? 'primary' : 'success'
                    "
                    size="mini"
                    style="margin-right: 8px"
                  >
                    {{ report.reportType === "weekly" ? "周报" : "月报" }}
                  </el-tag>
                  <span class="report-title">{{ report.title }}</span>
                </div>
                <span class="report-date">{{
                  parseTime(report.createTime, "{y}-{m}-{d}")
                }}</span>
              </div>
            </div>
          </div>
        </el-card>
        <!-- 预览弹窗 -->
        <el-dialog
          title="报告详情"
          :visible.sync="reportDialogVisible"
          width="60%"
          :append-to-body="true"
        >
          <div v-if="currentReport">
            <h3>{{ currentReport.title }}</h3>
            <div style="margin-bottom: 8px">
              <el-tag
                :type="
                  currentReport.reportType === 'weekly' ? 'primary' : 'success'
                "
              >
                {{ currentReport.reportType === "weekly" ? "周报" : "月报" }}
              </el-tag>
              <span style="margin-left: 12px">{{
                parseTime(currentReport.createTime, "{y}-{m}-{d} {h}:{i}")
              }}</span>
            </div>
            <el-divider></el-divider>
            <div
              style="max-height: 400px; overflow: auto; white-space: pre-line"
            >
              {{ currentReport.content }}
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="reportDialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="goToReportHistory"
              >进入全部报告</el-button
            >
          </div>
        </el-dialog>
      </el-col>
      <!-- 右侧：公告、快速操作、AI助手、最近文档 -->
      <el-col :lg="8" :md="24" class="right-col">
        <el-card class="notice-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="header-title">
              <i class="el-icon-bell"></i>
              最新公告
            </span>
            <el-radio-group
              v-model="noticeTab"
              size="mini"
              style="margin-left: 16px"
            >
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="notice">通知</el-radio-button>
              <el-radio-button label="announcement">公告</el-radio-button>
            </el-radio-group>
            <el-button type="text" @click="goToNotice">
              更多 <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          <div class="notice-content">
            <div
              v-if="
                (noticeTab === 'all'
                  ? allNotices
                  : noticeTab === 'notice'
                  ? noticeNotices
                  : announcementNotices
                ).length === 0
              "
              class="empty-notice"
            >
              <i class="el-icon-bell"></i>
              <p>暂无公告</p>
            </div>
            <div v-else class="notice-list">
              <div
                v-for="notice in noticeTab === 'all'
                  ? allNotices
                  : noticeTab === 'notice'
                  ? noticeNotices
                  : announcementNotices"
                :key="notice.noticeId"
                class="notice-item"
                @click="viewNotice(notice)"
              >
                <div class="notice-type">
                  <el-tag
                    :type="notice.noticeType === '1' ? 'primary' : 'success'"
                    size="mini"
                  >
                    {{ notice.noticeType === "1" ? "通知" : "公告" }}
                  </el-tag>
                </div>
                <div class="notice-info">
                  <div class="notice-title">{{ notice.noticeTitle }}</div>
                  <div class="notice-time">
                    {{ formatDate(notice.createTime) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <el-card class="quick-actions-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="header-title">
              <i class="el-icon-menu"></i>
              快速操作
            </span>
          </div>
          <div class="quick-actions">
            <div class="action-grid">
              <div
                v-for="action in quickActions"
                :key="action.key"
                class="action-item"
                @click="handleQuickAction(action)"
              >
                <div
                  class="action-icon"
                  :style="{ backgroundColor: action.color }"
                >
                  <i :class="action.icon"></i>
                </div>
                <div class="action-text">{{ action.name }}</div>
              </div>
            </div>
          </div>
        </el-card>
        <el-card class="ai-assistant-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="header-title">
              <i class="el-icon-s-help"></i>
              智能助手
            </span>
          </div>
          <div class="ai-content">
            <div class="ai-avatar">
              <img src="@/assets/ai-avatar.png" alt="AI助手" />
            </div>
            <div class="ai-message">
              <p>{{ aiMessage }}</p>
            </div>
            <div class="ai-actions">
              <el-button type="primary" size="small" @click="startChat">
                开始对话
              </el-button>
              <el-button size="small" @click="askQuestion">
                快速提问
              </el-button>
            </div>
          </div>
        </el-card>
        <el-card class="recent-docs-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="header-title">
              <i class="el-icon-document"></i>
              最近文档
            </span>
            <el-button type="text" @click="goToDocumentManage">
              更多 <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
          <div class="recent-docs-content">
            <div v-if="recentDocs.length === 0" class="empty-recent-docs">
              <i class="el-icon-document"></i>
              <p>暂无最近文档</p>
            </div>
            <div v-else class="recent-docs-list">
              <div
                v-for="doc in recentDocs"
                :key="doc.ossId"
                class="recent-doc-item"
                @click="previewRecentDoc(doc)"
              >
                <i
                  :class="getFileIcon(doc.originalName)"
                  style="margin-right: 8px"
                ></i>
                <span class="doc-title">{{ doc.originalName }}</span>
                <span class="doc-date">{{ formatDate(doc.createTime) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 在页面底部插入AI助手侧边栏 -->
    <!-- AI助手弹窗 -->
    <el-dialog
      title="AI助手"
      :visible.sync="aiAssistantOpen"
      width="500px"
      top="10vh"
      :close-on-click-modal="false"
      custom-class="ai-assistant-dialog"
      append-to-body
    >
      <div class="ai-chat-area">
        <div class="ai-messages" ref="aiMessageList">
          <div
            v-for="(message, index) in aiMessages"
            :key="index"
            class="ai-message-item"
            :class="{
              'ai-message': message.type === 'ai',
              'user-message': message.type === 'user',
            }"
          >
            <div v-if="message.type === 'ai'" class="ai-message-content">
              <div class="ai-avatar-small">
                <img src="@/assets/ai-avatar.png" alt="AI" />
              </div>
              <div class="ai-message-bubble">
                <div
                  class="ai-message-text"
                  v-html="formatMessage(message.content)"
                ></div>
                <div class="ai-message-time">
                  {{ formatTime(message.timestamp) }}
                </div>
              </div>
            </div>
            <div v-else class="user-message-content">
              <div class="user-message-bubble">
                <div class="user-message-text">{{ message.content }}</div>
                <div class="user-message-time">
                  {{ formatTime(message.timestamp) }}
                </div>
              </div>
              <div class="user-avatar-small">
                <div class="avatar-container">
                  <img
                    :src="avatar || defaultAvatar"
                    :alt="nickName || name"
                    @error="handleAvatarError"
                  />
                  <div class="online-indicator"></div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="aiLoading" class="ai-message-item">
            <div class="ai-message-content">
              <div class="ai-avatar-small">
                <img src="@/assets/ai-avatar.png" alt="AI" />
              </div>
              <div class="ai-message-bubble">
                <div class="ai-message-text">
                  <div class="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="ai-input-area">
          <el-input
            v-model="aiInputMessage"
            type="textarea"
            :rows="2"
            placeholder="向AI助手提问..."
            @keydown.ctrl.enter="sendAIMessage"
            :disabled="!aiConnected"
            resize="none"
          />
          <div class="ai-input-actions">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-s-promotion"
              @click="sendAIMessage"
              :disabled="!aiInputMessage.trim() || !aiConnected || aiLoading"
              :loading="aiLoading"
            >
              发送
            </el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="clearAIChat"
              :disabled="aiMessages.length === 0"
              style="margin-left: 8px"
            >
              清空
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 文档预览弹窗 -->
    <el-dialog
      title="文档预览"
      :visible.sync="previewDocDialog"
      width="80%"
      :append-to-body="true"
      :lock-scroll="true"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      custom-class="preview-dialog"
      top="5vh"
    >
      <div class="preview-container">
        <iframe
          v-if="
            previewDocUrl &&
            !previewDocIsImage &&
            !previewDocIsText &&
            !previewDocIsPdf
          "
          :src="previewDocUrl"
          frameborder="0"
          class="preview-iframe"
        ></iframe>
        <img
          v-else-if="previewDocUrl && previewDocIsImage"
          :src="previewDocUrl"
          class="preview-image"
          alt="文件预览"
        />
        <div
          v-else-if="previewDocText && previewDocIsText"
          class="preview-text"
          v-html="previewDocText"
        ></div>
        <iframe
          v-else-if="previewDocUrl && previewDocIsPdf"
          :src="previewDocUrl"
          frameborder="0"
          class="preview-iframe pdf-iframe"
        ></iframe>
        <div v-else class="preview-error">
          <i class="el-icon-warning"></i>
          <p>该文件类型暂不支持预览</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CountTo from "vue-count-to";
import { listSchedule } from "@/api/system/schedule";
import { listNotice } from "@/api/system/notice";
import { getStats } from "@/api/system/oss";
import { getKnowledgeBaseStats } from "@/api/rag";
import { getReportStatistics } from "@/api/report";
import { mapGetters } from "vuex";
import { generateAnswer } from "@/api/ollama";

export default {
  name: "Dashboard",
  components: {
    CountTo,
  },
  data() {
    return {
      // 统计数据
      statsData: [
        {
          title: "知识库数量",
          value: 0,
          icon: "el-icon-folder",
          trend: 12,
          key: "knowledge",
        },
        {
          title: "文档处理量",
          value: 0,
          icon: "el-icon-document",
          trend: 8,
          key: "document",
        },
        {
          title: "日程安排",
          value: 0,
          icon: "el-icon-date",
          trend: -5,
          key: "schedule",
        },
        {
          title: "公告数量",
          value: 0,
          icon: "el-icon-bell",
          trend: 15,
          key: "notice",
        },
      ],
      // 今日日程
      todaySchedules: [],
      // 全部日程（用于同步即将到来的日程数量）
      allSchedules: [],
      // 最新公告
      notices: [],
      // 快速操作
      quickActions: [
        {
          name: "上传文档",
          icon: "el-icon-upload",
          color: "#409EFF",
          key: "upload",
        },
        {
          name: "创建日程",
          icon: "el-icon-date",
          color: "#67C23A",
          key: "schedule",
        },
        {
          name: "知识库",
          icon: "el-icon-folder",
          color: "#E6A23C",
          key: "knowledge",
        },
        {
          name: "智能对话",
          icon: "el-icon-chat-dot-round",
          color: "#F56C6C",
          key: "chat",
        },
        {
          name: "周报月报",
          icon: "el-icon-data-analysis",
          color: "#909399",
          key: "report",
        },
        {
          name: "群聊私有助手",
          icon: "el-icon-chat-line-round",
          color: "#9C27B0",
          key: "privateChat",
        },
      ],
      // AI助手消息
      aiMessage:
        "您好！我是您的智能办公助手，可以帮助您处理文档、管理日程、回答问题等。有什么需要帮助的吗？",
      // 当前日期
      currentDate: "",
      // AI助手侧边栏
      aiAssistantOpen: false,
      aiConnected: true,
      aiMessages: [],
      aiInputMessage: "",
      aiLoading: false,
      defaultAvatar: require("@/assets/images/profile.jpg"),
      scheduleTab: "today",
      weekSchedules: [],
      upcomingSchedules: [],
      noticeTab: "all",
      allNotices: [],
      noticeNotices: [],
      announcementNotices: [],
      recentDocs: [],
      previewDocDialog: false,
      previewDocUrl: "",
      previewDocType: "",
      previewDocIsImage: false,
      previewDocIsText: false,
      previewDocIsPdf: false,
      previewDocText: "",
      weeklyReports: [], // 新增：周报/日报列表
      reportDialogVisible: false, // 新增：报告预览弹窗
      currentReport: null, // 新增：当前预览报告
      meetings: [], // 新增：会议管理列表
    };
  },
  computed: {
    ...mapGetters(["name", "nickName", "avatar"]),
  },
  created() {
    this.initData();
    this.setCurrentDate();
    this.addAIWelcomeMessage();
    this.loadWeekSchedules();
    this.loadUpcomingSchedules();
    this.loadRecentDocs();
    this.loadWeeklyReports(); // 新增
  },
  methods: {
    // 初始化数据
    async initData() {
      await Promise.all([
        this.loadStatistics(),
        this.loadTodaySchedules(),
        this.loadNotices(),
        this.loadAllSchedulesAndSyncUpcomingCount(),
      ]);
    },

    // 设置当前日期
    setCurrentDate() {
      const now = new Date();
      const options = {
        year: "numeric",
        month: "long",
        day: "numeric",
        weekday: "long",
      };
      this.currentDate = now.toLocaleDateString("zh-CN", options);
    },

    // 获取问候语
    getGreeting() {
      const hour = new Date().getHours();
      if (hour < 6) return "夜深了";
      if (hour < 9) return "早上好";
      if (hour < 12) return "上午好";
      if (hour < 14) return "中午好";
      if (hour < 18) return "下午好";
      if (hour < 22) return "晚上好";
      return "夜深了";
    },

    // 加载统计数据
    async loadStatistics() {
      try {
        // 获取知识库统计
        const kbStats = await getKnowledgeBaseStats();
        if (kbStats.code === "0000") {
          this.statsData[0].value = kbStats.data.totalTags || 0;
        }

        // 获取文档统计
        const docStats = await getStats();
        if (docStats.code === 200) {
          this.statsData[1].value = docStats.data.totalDocuments || 0;
        }

        // 获取报告统计
        const reportStats = await getReportStatistics();
        if (reportStats.code === 200) {
          // this.statsData[2].value = reportStats.data.weeklyCount || 0;
        }
      } catch (error) {
        console.error("加载统计数据失败:", error);
      }
    },

    // 加载今日日程
    async loadTodaySchedules() {
      try {
        const today = new Date();
        const startOfDay = new Date(
          today.getFullYear(),
          today.getMonth(),
          today.getDate()
        );
        const endOfDay = new Date(
          today.getFullYear(),
          today.getMonth(),
          today.getDate(),
          23,
          59,
          59
        );

        const params = {
          startTime: startOfDay.toISOString(),
          endTime: endOfDay.toISOString(),
        };

        const response = await listSchedule(params);
        if (response.code === 200) {
          this.todaySchedules = response.rows || [];
          // 统计卡片"日程安排"数量与今日实际日程同步
          // this.statsData[2].value = this.todaySchedules.length;
        }
      } catch (error) {
        console.error("加载今日日程失败:", error);
      }
    },

    // 加载公告
    async loadNotices() {
      try {
        const params = {
          pageNum: 1,
          pageSize: 5,
        };
        const response = await listNotice(params);
        if (response.code === 200) {
          this.allNotices = response.rows || [];
          this.noticeNotices = this.allNotices.filter(
            (n) => n.noticeType === "1"
          );
          this.announcementNotices = this.allNotices.filter(
            (n) => n.noticeType === "2"
          );
          this.notices = this.allNotices;
          this.statsData[3].value = response.total || this.notices.length;
        }
      } catch (error) {
        console.error("加载公告失败:", error);
      }
    },

    // 新增：加载全部日程并同步即将到来的日程数量
    async loadAllSchedulesAndSyncUpcomingCount() {
      try {
        // 不传参数获取全部日程
        const response = await listSchedule();
        if (response.code === 200) {
          this.allSchedules = response.rows || [];
          // 过滤即将到来的日程
          const upcoming = this.getUpcomingSchedules(this.allSchedules);
          // statsData[2]为"日程安排"
          this.statsData[2].value = upcoming.length;
        }
      } catch (error) {
        console.error("同步即将到来的日程数量失败:", error);
      }
    },

    // 新增：获取即将到来的日程（与schedule/index.vue逻辑一致）
    getUpcomingSchedules(schedules) {
      const now = new Date();
      return (schedules || [])
        .filter((item) => {
          const startTime = new Date(item.startTime);
          const endTime = new Date(item.endTime);
          // 显示即将开始或正在进行的日程
          return startTime > now || (startTime <= now && endTime > now);
        })
        .sort((a, b) => new Date(a.startTime) - new Date(b.startTime))
        .slice(0, 5); // 只显示前5个，与schedule一致
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return "";
      const time = new Date(timeStr);
      return time.toLocaleTimeString("zh-CN", {
        hour: "2-digit",
        minute: "2-digit",
      });
    },

    // 获取时长
    getDuration(startTime, endTime) {
      if (!startTime || !endTime) return "";
      const start = new Date(startTime);
      const end = new Date(endTime);
      const diff = end - start;
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      return `${hours}小时${minutes}分钟`;
    },

    // 判断是否紧急
    isUrgent(schedule) {
      const now = new Date();
      const scheduleTime = new Date(schedule.startTime);
      const diff = scheduleTime - now;
      return diff > 0 && diff <= 30 * 60 * 1000; // 30分钟内
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      return date.toLocaleDateString("zh-CN");
    },

    // 卡片点击事件
    handleCardClick(item) {
      switch (item.key) {
        case "knowledge":
          this.$router.push("/repository");
          break;
        case "document":
          this.$router.push("/documentation/documentManage");
          break;
        case "schedule":
          this.$router.push("/AIhelp/schedule");
          break;
        case "notice":
          this.$router.push("/system/notice");
          break;
      }
    },

    // 快速操作处理
    handleQuickAction(action) {
      switch (action.key) {
        case "upload":
          this.$router.push("/wendang");
          break;
        case "schedule":
          this.addSchedule();
          break;
        case "knowledge":
          this.$router.push("/repository");
          break;
        case "chat":
          this.$router.push("/AIhelp/zhineng");
          break;
        case "report":
          this.$router.push("/date/weekly-report");
          break;
        case "privateChat":
          this.$router.push("/AIhelp/peopleChat");
          break;
      }
    },

    // 添加日程
    addSchedule() {
      this.$router.push("/AIhelp/schedule");
    },

    // 编辑日程
    editSchedule(schedule) {
      this.$router.push(`/AIhelp/schedule?edit=${schedule.id}`);
    },

    // 查看公告
    viewNotice(notice) {
      this.$router.push(`/system/notice?view=${notice.noticeId}`);
    },

    // 跳转到日程页面
    goToSchedule() {
      this.$router.push("/AIhelp/schedule");
    },

    // 跳转到公告页面
    goToNotice() {
      this.$router.push("/system/notice");
    },

    // 开始对话
    startChat() {
      this.$router.push("/AIhelp/zhineng");
    },

    // 快速提问
    askQuestion() {
      this.aiAssistantOpen = true;
    },

    // 清空聊天记录
    clearAIChat() {
      this.$confirm("确定要清空AI助手的聊天记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.aiMessages = [];
          this.aiInputMessage = "";
          this.addAIWelcomeMessage();
          this.$message.success("AI助手聊天记录已清空");
        })
        .catch(() => {});
    },

    // 处理AI消息
    formatMessage(content) {
      return content
        .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>")
        .replace(/\*(.*?)\*/g, "<em>$1</em>")
        .replace(/`(.*?)`/g, "<code>$1</code>")
        .replace(/\n/g, "<br>");
    },

    // 处理头像加载错误
    handleAvatarError(event) {
      event.target.src = this.defaultAvatar;
    },

    // AI助手相关方法
    async sendAIMessage() {
      if (!this.aiInputMessage.trim() || !this.aiConnected) return;
      const message = {
        type: "user",
        username: this.nickName || this.name,
        avatar: this.avatar,
        content: this.aiInputMessage.trim(),
        timestamp: Date.now(),
      };
      this.addAIMessage(message);
      this.aiInputMessage = "";
      await this.generateAIResponse(message.content, message.username);
    },
    async generateAIResponse(userMessage, username) {
      this.aiLoading = true;
      try {
        const prompt = this.buildAIPrompt(userMessage, username);
        const response = await generateAnswer("deepseek-r1:1.5b", prompt);
        if (response.result) {
          const content = response.result.output?.content;
          if (content) {
            const cleanContent = content.replace(
              /<think>[\s\S]*?<\/think>\n\n/,
              ""
            );
            const aiMessage = {
              type: "ai",
              content: cleanContent,
              timestamp: Date.now(),
            };
            this.addAIMessage(aiMessage);
          } else {
            throw new Error("获取回复失败：响应格式不正确");
          }
        } else {
          throw new Error("获取回复失败：服务器响应为空");
        }
      } catch (error) {
        this.$message.error("AI回复生成失败: " + (error.message || "未知错误"));
        const errorMessage = {
          type: "ai",
          content: "抱歉，我暂时无法回答您的问题，请稍后再试。",
          timestamp: Date.now(),
        };
        this.addAIMessage(errorMessage);
      } finally {
        this.aiLoading = false;
      }
    },
    buildAIPrompt(userMessage, username) {
      const currentTime = new Date().toLocaleString("zh-CN");
      return `你是一个专业的办公助手，专门为办公场景提供帮助。\n\n用户信息：\n- 用户名：${username}\n- 当前时间：${currentTime}\n\n用户问题：${userMessage}\n\n请以友好、专业、简洁的方式回答用户的问题。回答要：\n1. 准确、有用\n2. 语言简洁明了\n3. 符合办公场景\n4. 适当使用表情符号增加亲和力\n5. 如果问题不明确，可以适当询问\n\n请直接回答，不要包含"作为AI助手"等前缀。`;
    },
    addAIMessage(message) {
      this.aiMessages.push(message);
      this.$nextTick(() => {
        this.scrollToAIBottom();
      });
    },
    addAIWelcomeMessage() {
      this.addAIMessage({
        type: "ai",
        content: `您好！我是您的AI助手，可以帮您解答问题、提供建议。有什么需要帮助的吗？`,
        timestamp: Date.now(),
      });
    },
    scrollToAIBottom() {
      const aiMessageList = this.$refs.aiMessageList;
      if (aiMessageList) {
        aiMessageList.scrollTop = aiMessageList.scrollHeight;
      }
    },
    // 判断日程状态（未开始/进行中/已结束）
    getScheduleStatus(schedule) {
      const now = new Date();
      const start = new Date(schedule.startTime);
      const end = new Date(schedule.endTime);
      if (now < start) {
        return { type: "info", text: "未开始" };
      } else if (now >= start && now < end) {
        return { type: "warning", text: "进行中" };
      } else {
        return { type: "success", text: "已结束" };
      }
    },
    async loadWeekSchedules() {
      try {
        const today = new Date();
        const startOfWeek = new Date(today);
        startOfWeek.setDate(today.getDate() - today.getDay() + 1);
        startOfWeek.setHours(0, 0, 0, 0);
        const endOfWeek = new Date(startOfWeek);
        endOfWeek.setDate(startOfWeek.getDate() + 6);
        endOfWeek.setHours(23, 59, 59, 999);
        const params = {
          startTime: startOfWeek.toISOString(),
          endTime: endOfWeek.toISOString(),
        };
        const response = await listSchedule(params);
        if (response.code === 200) {
          this.weekSchedules = response.rows || [];
        }
      } catch (error) {
        console.error("加载本周日程失败:", error);
      }
    },
    async loadUpcomingSchedules() {
      try {
        const response = await listSchedule();
        if (response.code === 200) {
          this.upcomingSchedules = this.getUpcomingSchedules(
            response.rows || []
          );
        }
      } catch (error) {
        console.error("加载即将到来的日程失败:", error);
      }
    },
    async loadRecentDocs() {
      try {
        // 获取最近10个文档，按上传时间倒序
        const res = await this.$http.get("/system/oss/list", {
          params: {
            pageNum: 1,
            pageSize: 10,
            orderByColumn: "createTime",
            isAsc: "desc",
          },
        });
        if (res.code === 200) {
          this.recentDocs = res.rows || [];
        } else {
          this.recentDocs = [];
        }
      } catch (error) {
        this.recentDocs = [];
      }
    },
    previewRecentDoc(doc) {
      // 预览文档，弹窗展示
      this.previewDocDialog = true;
      this.previewDocUrl = `/system/oss/download/${doc.ossId}`;
      const ext = doc.originalName.split(".").pop().toLowerCase();
      this.previewDocType = ext;
      this.previewDocIsImage = ["jpg", "jpeg", "png", "gif"].includes(ext);
      this.previewDocIsText = ["txt", "md", "csv"].includes(ext);
      this.previewDocIsPdf = ext === "pdf";
      if (this.previewDocIsText) {
        // 获取文本内容
        this.$http.get(this.previewDocUrl).then((res) => {
          this.previewDocText = res.data;
        });
      }
    },
    goToDocumentManage() {
      this.$router.push("/documentation/documentManage");
    },
    getFileIcon(fileName) {
      const ext = fileName.split(".").pop().toLowerCase();
      const iconMap = {
        pdf: "el-icon-document",
        doc: "el-icon-document",
        docx: "el-icon-document",
        xls: "el-icon-document",
        xlsx: "el-icon-document",
        ppt: "el-icon-document",
        pptx: "el-icon-document",
        txt: "el-icon-document",
        jpg: "el-icon-picture",
        jpeg: "el-icon-picture",
        png: "el-icon-picture",
        gif: "el-icon-picture",
        zip: "el-icon-folder",
        rar: "el-icon-folder",
        mp4: "el-icon-video-camera",
        mp3: "el-icon-headset",
      };
      return iconMap[ext] || "el-icon-document";
    },
    async loadWeeklyReports() {
      try {
        const params = { pageNum: 1, pageSize: 3 };
        const res = await this.$http.get("/system/report/v1/history", {
          params,
        });
        if (res.code === 200) {
          this.weeklyReports = res.rows || [];
        } else {
          this.weeklyReports = [];
        }
      } catch (e) {
        this.weeklyReports = [];
      }
    },
    previewReport(report) {
      this.currentReport = report;
      this.reportDialogVisible = true;
    },
    goToReportHistory() {
      this.$router.push("/date/report-history");
    },
    parseTime(time, pattern) {
      // 复用office工具
      if (!time) return "";
      const date = new Date(time);
      const y = date.getFullYear();
      const m = (date.getMonth() + 1).toString().padStart(2, "0");
      const d = date.getDate().toString().padStart(2, "0");
      const h = date.getHours().toString().padStart(2, "0");
      const i = date.getMinutes().toString().padStart(2, "0");
      if (pattern === "{y}-{m}-{d}") return `${y}-${m}-${d}`;
      if (pattern === "{y}-{m}-{d} {h}:{i}") return `${y}-${m}-${d} ${h}:${i}`;
      return `${y}-${m}-${d}`;
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

// 欢迎横幅
.welcome-banner {
  position: relative;
  background: linear-gradient(120deg, #667eea 0%, #43e97b 100%);
  border-radius: 16px;
  padding: 36px 32px 56px 32px;
  margin-bottom: 28px;
  color: #fff;
  overflow: hidden;
  box-shadow: 0 4px 32px rgba(67, 233, 123, 0.08);
  .welcome-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .welcome-text {
      .ai-title-row {
        display: flex;
        align-items: center;
        gap: 12px;
        h2 {
          margin: 0;
          font-size: 30px;
          font-weight: 800;
          letter-spacing: 1px;
          text-shadow: 0 2px 8px rgba(67, 233, 123, 0.12);
        }
        .ai-icon {
          width: 38px;
          height: 38px;
          filter: drop-shadow(0 2px 8px rgba(67, 233, 123, 0.18));
        }
      }
      .welcome-subtitle {
        font-size: 16px;
        font-weight: 500;
        margin: 8px 0 10px 0;
        opacity: 0.92;
        letter-spacing: 0.5px;
      }
      p {
        margin: 0;
        font-size: 14px;
        opacity: 0.9;
      }
    }
    .welcome-avatar {
      position: relative;
      .el-avatar {
        border: 3px solid rgba(255, 255, 255, 0.3);
        box-shadow: 0 2px 12px rgba(67, 233, 123, 0.18);
      }
      .ai-badge {
        position: absolute;
        right: -8px;
        bottom: -8px;
        width: 28px;
        height: 28px;
        border-radius: 50%;
        background: #fff;
        box-shadow: 0 2px 8px rgba(67, 233, 123, 0.18);
        border: 2px solid #43e97b;
        padding: 2px;
      }
    }
  }
  .banner-wave {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 48px;
    background: url('data:image/svg+xml;utf8,<svg width="100%" height="48" viewBox="0 0 1440 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0 24C120 48 360 48 720 24C1080 0 1320 0 1440 24V48H0V24Z" fill="%23ffffff22"/></svg>')
      repeat-x;
    background-size: cover;
    pointer-events: none;
  }
}

// 统计卡片
.stats-row {
  margin-bottom: 24px;

  .stats-card {
    background: white;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.3s ease;
    height: 120px;
    display: flex;
    align-items: center;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }

    .stats-icon {
      width: 60px;
      height: 60px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;

      i {
        font-size: 28px;
        color: white;
      }
    }

    .stats-content {
      flex: 1;

      .stats-value {
        font-size: 28px;
        font-weight: 700;
        color: #303133;
        margin-bottom: 4px;
      }

      .stats-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }

      .stats-trend {
        font-size: 12px;

        .trend-up {
          color: #67c23a;
        }

        .trend-down {
          color: #f56c6c;
        }
      }
    }

    &.stats-card-1 .stats-icon {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.stats-card-2 .stats-icon {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    &.stats-card-3 .stats-icon {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }

    &.stats-card-4 .stats-icon {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
  }
}

// 主要内容区域
.main-content {
  display: flex;
  align-items: stretch;
  min-height: 600px;
  height: 100%;
}

.left-col {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.right-col {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.right-col .el-card {
  flex: 1 1 auto;
  min-height: 0;
  overflow: auto;
  margin-bottom: 20px;
}

.schedule-card {
  flex: 1 1 auto;
  min-height: 320px;
  margin-bottom: 20px;
}

.weekly-report-card {
  flex: 0 0 auto;
  min-height: 180px;
}

.schedule-content {
  .empty-schedule {
    text-align: center;
    padding: 40px 20px;
    color: #909399;

    i {
      font-size: 48px;
      margin-bottom: 16px;
      display: block;
    }

    p {
      margin: 0 0 16px 0;
      font-size: 14px;
    }
  }

  .schedule-list {
    .schedule-item {
      display: flex;
      align-items: center;
      padding: 16px;
      border-radius: 8px;
      margin-bottom: 12px;
      background: #f8f9fa;
      transition: all 0.3s ease;

      &:hover {
        background: #e3f2fd;
      }

      &.urgent {
        background: #fff3e0;
        border-left: 4px solid #ff9800;
      }

      .schedule-time {
        text-align: center;
        margin-right: 16px;
        min-width: 80px;

        .time {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }

        .duration {
          font-size: 12px;
          color: #909399;
          margin-top: 4px;
        }
      }

      .schedule-info {
        flex: 1;

        .schedule-title {
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
        }

        .schedule-status {
          margin-bottom: 2px;
        }

        .schedule-location,
        .schedule-participants {
          font-size: 12px;
          color: #909399;
          margin-bottom: 2px;

          i {
            margin-right: 4px;
          }
        }
      }

      .schedule-actions {
        .el-button {
          padding: 4px;
        }
      }
    }
  }
}

// 公告卡片
.notice-content {
  .empty-notice {
    text-align: center;
    padding: 40px 20px;
    color: #909399;

    i {
      font-size: 48px;
      margin-bottom: 16px;
      display: block;
    }

    p {
      margin: 0;
      font-size: 14px;
    }
  }

  .notice-list {
    .notice-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      transition: all 0.3s ease;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background: #f8f9fa;
        padding-left: 8px;
        padding-right: 8px;
        border-radius: 6px;
      }

      .notice-type {
        margin-right: 12px;
      }

      .notice-info {
        flex: 1;

        .notice-title {
          font-size: 14px;
          color: #303133;
          margin-bottom: 4px;
          line-height: 1.4;
        }

        .notice-time {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

// 快速操作卡片
.quick-actions {
  .action-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;

    .action-item {
      text-align: center;
      padding: 16px 8px;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: #f8f9fa;
        transform: translateY(-2px);
      }

      .action-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 8px;

        i {
          font-size: 24px;
          color: white;
        }
      }

      .action-text {
        font-size: 12px;
        color: #606266;
        font-weight: 500;
      }
    }
  }
}

// 智能助手卡片
.ai-assistant-card {
  .ai-content {
    text-align: center;
    padding: 20px;

    .ai-avatar {
      margin-bottom: 16px;

      img {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        border: 3px solid #e3f2fd;
      }
    }

    .ai-message {
      margin-bottom: 20px;

      p {
        margin: 0;
        font-size: 14px;
        color: #606266;
        line-height: 1.6;
      }
    }

    .ai-actions {
      display: flex;
      gap: 12px;
      justify-content: center;
    }
  }
}

// 最近文档卡片
.recent-docs-card {
  .recent-docs-content {
    .empty-recent-docs {
      text-align: center;
      padding: 40px 20px;
      color: #909399;
      i {
        font-size: 48px;
        margin-bottom: 16px;
        display: block;
      }
      p {
        margin: 0;
        font-size: 14px;
      }
    }
    .recent-docs-list {
      .recent-doc-item {
        display: flex;
        align-items: center;
        padding: 10px 0;
        border-bottom: 1px solid #f0f0f0;
        cursor: pointer;
        transition: all 0.3s ease;
        &:last-child {
          border-bottom: none;
        }
        &:hover {
          background: #f8f9fa;
          padding-left: 8px;
          padding-right: 8px;
          border-radius: 6px;
        }
        .doc-title {
          flex: 1;
          font-size: 14px;
          color: #303133;
        }
        .doc-date {
          font-size: 12px;
          color: #909399;
          margin-left: 12px;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard-container {
    padding: 12px;
  }

  .welcome-banner {
    padding: 16px;

    .welcome-content {
      flex-direction: column;
      text-align: center;

      .welcome-avatar {
        margin-top: 16px;
      }
    }
  }

  .stats-row {
    .stats-card {
      height: auto;
      padding: 16px;

      .stats-icon {
        width: 48px;
        height: 48px;
        margin-right: 12px;

        i {
          font-size: 24px;
        }
      }

      .stats-content {
        .stats-value {
          font-size: 24px;
        }
      }
    }
  }

  .quick-actions {
    .action-grid {
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;
    }
  }
}

/* 弹窗AI助手样式 */
::v-deep .ai-assistant-dialog {
  z-index: 3000 !important;
}
::v-deep .el-dialog__wrapper {
  z-index: 3000 !important;
}
.ai-chat-area {
  max-height: 60vh;
  display: flex;
  flex-direction: column;
}
.ai-messages {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 10px;
  padding-top: 10px;
}
.ai-input-area {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
}
.ai-input-actions {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
.ai-message-item {
  display: flex;
  flex-direction: row;
  margin-bottom: 18px;
  align-items: flex-end;
}
.ai-message-content {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  width: 100%;
}
.ai-avatar-small,
.user-avatar-small {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}
.ai-avatar-small img,
.user-avatar-small img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}
.ai-message-bubble {
  max-width: 70%;
  background: #f0f9ff;
  padding: 10px 14px;
  border-radius: 10px 10px 10px 4px;
  font-size: 14px;
  line-height: 1.7;
  color: #303133;
  word-wrap: break-word;
  border-left: 3px solid #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.06);
}
.ai-message-time {
  font-size: 11px;
  color: #909399;
  margin-top: 6px;
  margin-left: 4px;
}
.user-message-content {
  display: flex;
  align-items: flex-start;
  flex-direction: row-reverse;
  gap: 10px;
  width: 100%;
}
.user-message-bubble {
  max-width: 70%;
  background: #e8f5e8;
  padding: 10px 14px;
  border-radius: 10px 10px 4px 10px;
  font-size: 14px;
  line-height: 1.7;
  color: #303133;
  word-wrap: break-word;
  border-right: 3px solid #67c23a;
  text-align: right;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.06);
}
.user-message-time {
  font-size: 11px;
  color: #909399;
  margin-top: 6px;
  margin-right: 4px;
  text-align: right;
}
</style> 